﻿using System;
using System.Collections.Generic;
using Nancy;
using Nancy.Bootstrapper;

namespace QQ2564874169.WebFx.Nancy.Middleware
{
    public class Forbidden
    {
        public List<string> Paths { get; private set; }

        public Forbidden(IPipelines pipelines)
        {
            Paths = new List<string>
            {
                "/app_data",
                "/appdata"
            };
            pipelines.BeforeRequest.AddItemToStartOfPipeline(OnBefore);
        }

        private Response OnBefore(NancyContext context)
        {
            if (IsForbidden(context.Request))
            {
                return new Response { StatusCode = HttpStatusCode.Forbidden }; 
            }
            return null;
        }

        protected virtual bool IsForbidden(Request request)
        {
            var path = request.Url.Path;
            foreach (var item in Paths)
            {
                if (path.StartsWith(item, StringComparison.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }
    }
}
